import { useContext } from "react";
import GanttContext from "../context";
import type { TaskMode } from "../types";
import { cn } from "../../../lib/utils";
import { Calendar } from "../components/icons";
import { getTotalWidth } from "../helpers/time";
import { GanttConsts } from "../constants";

interface TaskHeaderProps {
  title: string;
}
const ModeButton = ({
  mode,
  currentMode,
  onClick
}: {
  mode: string;
  currentMode: string;
  onClick: () => void
}) => (
  <div
    key={mode}
    className={cn(
      "h-8 w-16 flex justify-center items-center text-sm rounded-sm cursor-pointer border",
      {
        "bg-orange-500 text-gray-50": mode === currentMode,
        "hover:shadow-xl hover:bg-orange-100": mode !== currentMode,
      }
    )}
    onClick={onClick}
  >
    {mode}
  </div>
);

function TaskHeader({ title }: TaskHeaderProps) {
  const { taskMode, setTaskMode, setScrollLeft, tasksStart, tasksEnd, setTotalWidth } = useContext(GanttContext);

  const handleModeChange = (mode: string) => {
    setTaskMode(mode as TaskMode);
    setScrollLeft(0);
    setTotalWidth(getTotalWidth(tasksStart, tasksEnd, mode as TaskMode));
  };

  return (
    <>
      <div className="flex items-center">{title}</div>
      <div className="flex items-center gap-2">
        <div className="flex justify-center items-center rounded-sm h-8 w-8 bg-gray-50 shadow-lg border border-gray-100">
          <Calendar className="text-orange-500" size={16} />
        </div>
        {GanttConsts.TASK_MODE.map((mode) => (
          <ModeButton
            key={mode}
            mode={mode}
            currentMode={taskMode}
            onClick={() => handleModeChange(mode)}
          />
        ))}
      </div>
    </>
  );
}

export default TaskHeader;
